import { Component, OnInit } from '@angular/core';
import { Hero } from 'src/app/domain/heroes/hero';
import { HeroService } from 'src/app/service/hero.service';
import { MessagesService } from 'src/app/service/messages.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.scss']
})
export class HeroesComponent implements OnInit {
  heroes: Hero []
  selectedHero: Hero = null
  constructor(
    private heroService: HeroService,
    private messageServic: MessagesService
  ) { }

  ngOnInit() {
    this.getHeroes()
  }
  getHeroes() {
    this.heroService.getHeroes().subscribe(heroes=>{
      this.heroes = heroes
    })
  }
  add(name: string) {
    name = name.trim()
    if (!name) return
    this.heroService.addHero({name} as Hero).subscribe(()=>{
      this.getHeroes()
    })
  }
  delete(hero: Hero){
    this.heroService.deleteHero(hero).subscribe(()=>{
      this.heroes = this.heroes.filter(h => h !== hero);
    })
  }
  onSelectHero(hero: Hero) {
    this.messageServic.add(`select ${hero.name}`)
    this.selectedHero = hero
  }
}
